#!/usr/bin/env node

/**
 * cloudbase function:deploy 方法简化方法
 * ./deploy          全部云方法部署(--force)
 * ./deploy [name]   部署指定云方法(--force)
 * 
 * ./deploy -          删除全部云函数(腾讯云上的，本地不影响)
 * ./deploy - [name]   删除指定云函数(腾讯云上的，本地不影响)
 */
const fs = require('fs-extra')
const shelljs = require('shelljs')
const chalk = require('chalk')

function dealwithCloudFunctions(tmp=[], act='deploy'){
  let cmdstr = ''
  const force = act === 'deploy' ? '--force' : ''
  tmp = tmp.length ? tmp : (fs.readdirSync('./functions') || [])
  tmp.forEach(funname=>{
    const ignor = /^[\.]/.test(funname)
    if (!ignor) {
      if (cmdstr.length) {
        cmdstr += `&& tcb fn ${act} ${funname} -e ${envId} ${force} `
      } else {
        cmdstr = `tcb fn ${act} ${funname} -e ${envId} ${force} `
      }
    }
  })
  return cmdstr
}

let action = 'deploy'
const cloudset = require('../../configs/cloudset')
const argv = require('minimist')(process.argv.slice(2));
const envId = require('./cloudbaserc.json').envId || cloudset.envid
const tmp = argv._

if (!envId) {
  chalk.bold.red('请在configs/cloudset.js文件中配置 envid，或者在cloudbaserc.json文件中配置 envId')
  process.exit()
}

if (tmp.length) {
  if (tmp[0] === '-') {
    tmp.splice(0, 1)
    action = 'delete'
  }

  if (tmp[0] === '+') {
    tmp.splice(0, 1)
  }
}

const cmdstr = dealwithCloudFunctions(tmp, action)
if (cmdstr) {
  console.log(cmdstr);
  shelljs.exec(cmdstr).stdout
}